<?php
namespace Admin\Controller;
use Think\Controller;
/*
 ×规格管理控制器
 ×
 */
class SpecsController extends AdminController {
	public function index(){
			$result=M('spec a')->join('inner join '.C('DB_PREFIX').'specval  b on  a.specid=b.specid')
			 ->getField('b.specvalid, a.specid,a.name,a.memo,b.name as vname ');
			$specids=array();
			foreach ($result as $key => $value) {
				$specids[]=$value['specid'];
			}
			$specids=array_unique($specids);
			$res=array();
			foreach ($specids as $key => $value) {
				foreach ($result as $k => $v) {
					if($v['specid']==$value){
						$res[$v['specid']]['specval'].=$v['vname'].',';
						$res[$v['specid']]['memo']=$v['memo'];		
						$res[$v['specid']]['name']=$v['name'];		
					}
				}
			}
            $this->assign('specs',$res);
			$this->display();
	}
	public function  addSpec(){
		$this->display('addspec');
	}
	public function saveSpec(){
		//将规格插入规格表中，成功之后 得到specid之后 将规格值+specid 插入到规格值表中
		
		$data['name']=I('post.name','','strip_tags');
		$data['memo']=I('post.memo','','strip_tags');
		$val=I('post.specval','','strip_tags');
		$spec=M('spec');

		$specval=M('specval');



		$spec->startTrans();

		$specid=$spec->add($data);



        $map['specid']=$specid;
        foreach($val as $key=>$value){
          	$map['name']=$value;

          	$result=$specval->add($map);

          	if (!empty($specid) && !empty($result)) {
          		$spec->commit();
          		 echo "<script type='text/javascript'>alert('添加规格成功'); window.location.href='/index.php/Admin/Specs/index';</script>";

          	}else{
          		$spec->rollback();
          		break;
          		echo "<script type='text/javascript'>alert('添加规格失败'); window.history.go(-1);</script>";
          	}
          
          }
		

		/*if(!empty($result)){
           echo "<script type='text/javascript'>alert('添加规格成功'); window.location.href='/index.php/Admin/Specs/index';</script>";
		}else{
			echo "<script type='text/javascript'>alert('添加规格失败'); window.history.go(-1);</script>";
		}*/
		
		//var_dump($_POST);die;
	}
	public function editSpec(){
		echo '编辑规格';
	}
	public function delSpec(){
		//删除规格时需检测此规格下是否有产品
	}

}